package com.ruoyi.web.controller.system;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.domain.AttendanceRecord;
import com.ruoyi.common.domain.Emply;
import com.ruoyi.common.domain.Holidays;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.task.KqPersonTask;
import com.ruoyi.system.domain.CsceceeEmployee;
import com.ruoyi.system.domain.Statistics;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.KqCardRecord;
import com.ruoyi.system.service.IKqCardRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 打卡原始记录Controller
 * 
 * @author ruoyi
 * @date 2022-03-18
 */
@RestController
@RequestMapping("/system/attendance")
public class KqCardRecordController extends BaseController
{
    @Autowired
    private IKqCardRecordService kqCardRecordService;

    @Autowired
    private ISysJobService sysJobService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private com.ruoyi.system.service.ICsceceeEmployeeService ICsceceeEmployeeService;

    /**
     * 查询打卡原始记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:list')")
    @GetMapping("/list")
    public TableDataInfo list(KqCardRecord kqCardRecord)
    {
        if(kqCardRecord != null && kqCardRecord.getDateRange() != null && kqCardRecord.getDateRange().length > 0){
            String[] dateRange = kqCardRecord.getDateRange();
            kqCardRecord.setStartDate(dateRange[0] + " 00:00:00");
            kqCardRecord.setEndDate(dateRange[1] + " 23:59:59");
        }
        startPage();
        List<KqCardRecord> list = kqCardRecordService.selectKqCardRecordList(kqCardRecord);
        return getDataTable(list);
    }

    /**
     * 查询打卡原始记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:statistics:statistics')")
    @GetMapping("/getStatisticsRecord")
    public TableDataInfo getStatisticsRecord(KqCardRecord kqCardRecord)
    {
        if(kqCardRecord != null && kqCardRecord.getDateRange() != null && kqCardRecord.getDateRange().length > 0){
            String[] dateRange = kqCardRecord.getDateRange();
            kqCardRecord.setStartDate(dateRange[0] + " 00:00:00");
            kqCardRecord.setEndDate(dateRange[1] + " 23:59:59");
        }
        startPage();
        List<Statistics> list = kqCardRecordService.getStatisticsRecord(kqCardRecord);
        if(list != null && list.size() > 0){
            list.forEach(p -> {
                p.setCalDateText(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, p.getCalDate()));
//                p.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, p.getDrawtmbgn()));
//                p.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, p.getDrawtmend()));
            });
        }
        return getDataTable(list);
    }

    /**
     * 导出打卡原始记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:export')")
    @Log(title = "打卡原始记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KqCardRecord kqCardRecord)
    {
        if(kqCardRecord != null && kqCardRecord.getDateRange() != null && kqCardRecord.getDateRange().length > 0){
            String[] dateRange = kqCardRecord.getDateRange();
            kqCardRecord.setStartDate(dateRange[0] + " 00:00:00");
            kqCardRecord.setEndDate(dateRange[1] + " 23:59:59");
        }
//        startPage();
        List<Statistics> list = kqCardRecordService.getStatisticsRecord2(kqCardRecord);

        List<Statistics> zyList = new ArrayList<>();
        List<Statistics> ldList = new ArrayList<>();
        List<Statistics> allList = new ArrayList<>();


        CsceceeEmployee query = new CsceceeEmployee();
        query.setLdFlag(KqPersonTask.ldflag);
        List<CsceceeEmployee> AllData =ICsceceeEmployeeService.selectCsceceeEmployeeList(query);
        if(!CollectionUtils.isEmpty(AllData)) {
            empIds =  AllData.stream()
                    .map(data -> data.getEmployeeId()).collect(Collectors.toList());
        }

        if(!CollectionUtils.isEmpty(empIds)) {
            ldList = list.stream().filter(data -> empIds.contains(data.getEmployeeId())).collect(Collectors.toList());
            dealCdZtLd(ldList);
        }

        zyList = list.stream().filter(data -> !empIds.contains(data.getEmployeeId())).collect(Collectors.toList());
        dealCdZt(zyList);

        allList.addAll(ldList);
        allList.addAll(zyList);

        ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
        util.exportExcel(response, allList, "考勤记录");
    }

    private void dealCdZt(List<Statistics> list)  {
        int flag = 510;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.forEach(data -> {
            StringBuffer sb = new StringBuffer();
            if("工作日".equals(data.getRemark())) {
                try {
                    String inTime =data.getCalDateText() + " " + data.getDrawtmbgnText();
                    String outTime = data.getCalDateText() + " " + data.getDrawtmendText();
                    if(inTime.contains("未签入") || outTime.contains("未签出")) {
                        sb.append("缺卡,");
                    } else {
                        Date inTimeDate = sdf.parse(inTime);
                        Date outTimeDate = sdf.parse(outTime);

                        if(inTimeDate.after(sdf.parse(data.getCalDateText() + " 09:00:59"))) {
                            sb.append("迟到，");
                        }else if(inTimeDate.after(sdf.parse(data.getCalDateText() + " 08:30:59"))
                                &&inTimeDate.before(sdf.parse(data.getCalDateText() + " 09:00:59"))) {
                            if(Convert.toInt(data.getFactGs()) < flag) {
                                sb.append("早退，");
                            }
                        }
                        if(inTimeDate.before(sdf.parse(data.getCalDateText() + " 08:30:59"))
                                && outTimeDate.before(sdf.parse(data.getCalDateText() + " 17:00:59"))) {
                            sb.append("早退，");
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            data.setZtcd(sb.toString());
        });
    }


    private void dealCdZtLd(List<Statistics> list)  {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.forEach(data -> {
            StringBuffer sb = new StringBuffer();
            if("工作日".equals(data.getRemark())) {
                try {
                    String inTime =data.getCalDateText() + " " + data.getDrawtmbgnText();
                    String outTime = data.getCalDateText() + " " + data.getDrawtmendText();
                    if(inTime.contains("未签入") || outTime.contains("未签出")) {
                        sb.append("缺卡,");
                    } else {
                        Date inTimeDate = sdf.parse(inTime);
                        Date outTimeDate = sdf.parse(outTime);

                        if(inTimeDate.after(sdf.parse(data.getCalDateText() + " 08:30:59"))) {
                            sb.append("迟到，");
                        }
                        if(outTimeDate.before(sdf.parse(data.getCalDateText() + " 17:00:59"))
                        ) {
                            sb.append("早退，");
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            data.setZtcd(sb.toString());
            if(StringUtils.isNotEmpty(sb.toString())) {
                data.setStatusText("异常");
            }
        });
    }


    public List<String> empIds = new ArrayList<>();
    @PostMapping("/exportld")
    public void exportld(HttpServletResponse response, KqCardRecord kqCardRecord)
    {
        empIds.clear();
        CsceceeEmployee query = new CsceceeEmployee();
        query.setLdFlag(KqPersonTask.ldflag);
        List<CsceceeEmployee> AllData =ICsceceeEmployeeService.selectCsceceeEmployeeList(query);
        if(!CollectionUtils.isEmpty(AllData)) {
            empIds =  AllData.stream()
                    .map(data -> data.getEmployeeId()).collect(Collectors.toList());
        }

        if(kqCardRecord != null && kqCardRecord.getDateRange() != null && kqCardRecord.getDateRange().length > 0){
            String[] dateRange = kqCardRecord.getDateRange();
            kqCardRecord.setStartDate(dateRange[0] + " 00:00:00");
            kqCardRecord.setEndDate(dateRange[1] + " 23:59:59");
        }
//        startPage();
        if(!CollectionUtils.isEmpty(empIds)) {
            kqCardRecord.setEmpIds(empIds);
        }
        List<Statistics> list = kqCardRecordService.getStatisticsRecord2(kqCardRecord);
        list.forEach(data -> {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 迁入
                String inTime =data.getCalDateText() + " " + data.getDrawtmbgnText();
                // 迁出
                String outTime = data.getCalDateText() + " " + data.getDrawtmendText();
                try {
                    if(StringUtils.isEmpty(inTime) || StringUtils.isEmpty(outTime)
                        || inTime.contains("未签入") || outTime.contains("未签出")) {
                        data.setStatus(2);
                    } else {
                        if(sdf.parse(inTime).before(sdf.parse(data.getCalDateText() + " 09:00:59"))
                                && sdf.parse(outTime).after(sdf.parse(data.getCalDateText() + " 17:00:00"))
                        ) {
                            data.setStatus(1);
                        }else {
                            data.setStatus(2);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
        });
        dealCdZtLd(list);
        ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
        util.exportExcel(response, list, "领导考勤记录");
    }

    @PostMapping("/currentExportld")
    public void currentExportld(HttpServletResponse response, KqCardRecord kqCardRecord)
    {
        empIds.clear();
        String date = DateUtils.getDate();
        kqCardRecord.setStartDate(date + " 00:00:00");
        kqCardRecord.setEndDate(date + " 23:59:59");

        Holidays holiday = sysJobService.getHolidaysByDate(kqCardRecord.getStartDate(), kqCardRecord.getEndDate()).get(0);
        List<Emply> emplyList = sysJobService.getEmplyList();

        CsceceeEmployee query = new CsceceeEmployee();
        query.setLdFlag(KqPersonTask.ldflag);
        List<CsceceeEmployee> AllData =ICsceceeEmployeeService.selectCsceceeEmployeeList(query);
        if(!CollectionUtils.isEmpty(AllData)) {
            empIds =  AllData.stream()
                    .map(data -> data.getEmployeeId()).collect(Collectors.toList());
        }

        if(!CollectionUtils.isEmpty(empIds)) {
            emplyList = emplyList.stream().filter(data -> empIds.contains(data.getEmployeeId())).collect(Collectors.toList());
        }


        List<AttendanceRecord> attendanceRecordList = sysJobService.getToDayAttendanceInfo(date);
//        startPage();
        List<Statistics> list = kqCardRecordService.currentExport(kqCardRecord, holiday, emplyList, attendanceRecordList);
        dealCdZtLd(list);
        ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
        util.exportExcel(response, list, "领导当日考勤记录");
    }




    /**
     * 导出打卡原始记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:currentExport')")
    @Log(title = "打卡原始记录", businessType = BusinessType.EXPORT)
    @PostMapping("/currentExport")
    public void currentExport(HttpServletResponse response, KqCardRecord kqCardRecord)
    {
        String date = DateUtils.getDate();
        kqCardRecord.setStartDate(date + " 00:00:00");
        kqCardRecord.setEndDate(date + " 23:59:59");

        Holidays holiday = sysJobService.getHolidaysByDate(kqCardRecord.getStartDate(), kqCardRecord.getEndDate()).get(0);
        List<Emply> emplyList = sysJobService.getEmplyList();
        List<AttendanceRecord> attendanceRecordList = sysJobService.getToDayAttendanceInfo(date);
//        startPage();
        List<Statistics> list = kqCardRecordService.currentExport(kqCardRecord, holiday, emplyList, attendanceRecordList);


        List<Statistics> zyList = new ArrayList<>();
        List<Statistics> ldList = new ArrayList<>();
        List<Statistics> allList = new ArrayList<>();


        CsceceeEmployee query = new CsceceeEmployee();
        query.setLdFlag(KqPersonTask.ldflag);
        List<CsceceeEmployee> AllData =ICsceceeEmployeeService.selectCsceceeEmployeeList(query);
        if(!CollectionUtils.isEmpty(AllData)) {
            empIds =  AllData.stream()
                    .map(data -> data.getEmployeeId()).collect(Collectors.toList());
        }

        if(!CollectionUtils.isEmpty(empIds)) {
            ldList = list.stream().filter(data -> empIds.contains(data.getEmployeeId())).collect(Collectors.toList());
            dealCdZtLd(ldList);
        }

        zyList = list.stream().filter(data -> !empIds.contains(data.getEmployeeId())).collect(Collectors.toList());
        dealCdZt(zyList);

        allList.addAll(ldList);
        allList.addAll(zyList);


        ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
        util.exportExcel(response, allList, "考勤记录");
    }

    /**
     * 导出打卡原始记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:allExport')")
    @Log(title = "打卡原始记录", businessType = BusinessType.EXPORT)
    @PostMapping("/allExport")
    public void allExport(HttpServletResponse response, KqCardRecord kqCardRecord)
    {
        if(kqCardRecord != null && kqCardRecord.getDateRange() != null && kqCardRecord.getDateRange().length > 0){
            String[] dateRange = kqCardRecord.getDateRange();
            kqCardRecord.setStartDate(dateRange[0] + " 00:00:00");
            kqCardRecord.setEndDate(dateRange[1] + " 23:59:59");
        }
        List<SysDept> depts = deptService.selectDeptList2(null);
        for (SysDept dept: depts) {
            if(dept.getDeptId() == 1 || dept.getDeptId() == 2){
                continue;
            }
            kqCardRecord.setDeptId(Integer.valueOf(dept.getDeptId()+""));
            kqCardRecord.setDeptName(dept.getDeptName());
            List<Statistics> list = kqCardRecordService.getStatisticsRecord2(kqCardRecord);
            ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
            util.exportExcel(response, list, "考勤记录");
        }

    }

    /**
     * 获取打卡原始记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:query')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        return AjaxResult.success(kqCardRecordService.selectKqCardRecordByRecordId(recordId));
    }

    /**
     * 新增打卡原始记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:add')")
    @Log(title = "打卡原始记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KqCardRecord kqCardRecord)
    {
        return toAjax(kqCardRecordService.insertKqCardRecord(kqCardRecord));
    }

    /**
     * 修改打卡原始记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @Log(title = "打卡原始记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KqCardRecord kqCardRecord)
    {
        return toAjax(kqCardRecordService.updateKqCardRecord(kqCardRecord));
    }

    /**
     * 删除打卡原始记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:remove')")
    @Log(title = "打卡原始记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(kqCardRecordService.deleteKqCardRecordByRecordIds(recordIds));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/getDeptList")
    public AjaxResult getDeptList()
    {
        List<SysDept> depts = deptService.selectDeptList2(null);

        return AjaxResult.success(depts.stream().filter(p -> p.getDeptId() != 1 && p.getDeptId() != 2).collect(Collectors.toList()));
    }
}
